<template>
  <div class="containe">
    <div class="button-container">
      <el-button type="primary"  @click="dialogVisible = true">添加订单</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="borrower"
        label="借书人">
      </el-table-column>
      <el-table-column
        prop="bookname"
        label="书籍名称">
      </el-table-column>
      <el-table-column
        prop="grade"
        label="班级">
      </el-table-column>
      <el-table-column
        prop="boorwerTime"
        label="借书时间">
      </el-table-column>
      <el-table-column
        prop="return"
        label="是否归还">
      </el-table-column>
      <el-table-column label="操作"> 
        <template slot-scope="{row}">
          <el-button 
            :type="row.return === '已归还' ? 'danger' : 'primary'"
            @click="returnn(row)">
            {{ row.return === '已归还' ? '删除记录' : '点击归还' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加订单" :visible.sync="dialogVisible">
      <div>
        <el-form :label-position="labelPosition" label-width="80px" >
          <el-form-item label="借书人">
            <el-input v-model="form.borrower"></el-input>
          </el-form-item>
          <el-form-item label="书籍名称">
            <el-input v-model="form.book_name"></el-input>
          </el-form-item>
          <el-form-item label="班级">
            <el-input  v-model="form.grade"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBorrow ">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<style lang="scss">
.containe {
  padding: 20px;
  background-color: #fff;
  height: 95%;
  
  .button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
    
    .el-button {
      padding: 10px 20px;
    }
  }
  
  .el-table {
    margin-top: 0;
    
    .el-table__header-wrapper {
      height: 60px; 
      line-height: 60px;
      font-size: 20px;
      
      th.el-table__cell {
        padding: 4px 0; 
      }
    }
    
    .el-table-column {
      line-height: 1.4;  
    }
  }
}
</style>

<script>
export default {
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      form: {
        borrower: '',
        book_name: '',
        grade: ''
      },
      labelPosition: 'right'
    };
  },
  created() {
    this.fetchBorrowList();
  },
  methods: {
    fetchBorrowList() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:3000/api/borrow/list');
    
    xhr.onload = () => {
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText);
          if (response.success) {
            this.tableData = response.data;
          } else {
            this.$message.error(response.message || '获取数据失败');
          }
        } catch (e) {
          console.error('解析响应失败:', e);
          this.$message.error('数据格式错误');
        }
      } else {
        this.$message.error(`请求失败: ${xhr.statusText}`);
      }
    };
    
    xhr.onerror = () => {
      this.$message.error('网络请求失败');
    };
    
    xhr.send();
  },
    
    addBorrow() {
    if (!this.form.borrower || !this.form.book_name || !this.form.grade) {
      this.$message.error('请填写所有信息');
      return;
    }

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:3000/api/borrow/add');
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.timeout = 5000;
    xhr.ontimeout = () => {
      this.$message.error('请求超时');
    };
    
    xhr.onload = () => {
      try {
        const response = JSON.parse(xhr.responseText);
        if (xhr.status === 200) {
          if (response.success) {
            this.$message.success(response.message);
            this.dialogVisible = false;
            this.fetchBorrowList();
          } else {
            this.$message.error(response.message || '操作失败');
          }
        } else if (xhr.status === 400) {
          this.$message.error(`参数错误: ${response.message}`);
        } else {
          this.$message.error(`服务器错误: ${xhr.status} ${xhr.statusText}`);
        }
      } catch (e) {
        console.error('解析响应失败:', e);
        this.$message.error('响应格式错误');
      }
    };
    
    xhr.onerror = () => {
      this.$message.error('网络请求失败');
    };
    xhr.send(JSON.stringify({
      borrower: this.form.borrower,
      book_name: this.form.book_name,
      grade: this.form.grade
    }));
  },

    returnn(row) {
    if (row.return === '已归还') {
      // 删除操作
      this.$confirm('确认删除这条借阅记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:3000/api/borrow/delete');
        xhr.setRequestHeader('Content-Type', 'application/json');
        
        xhr.onload = () => {
          if (xhr.status === 200) {
            try {
              const response = JSON.parse(xhr.responseText);
              if (response.success) {
                this.$message.success(response.message);
                this.fetchBorrowList();
              } else {
                this.$message.error(response.message || '删除失败');
              }
            } catch (e) {
              console.error('解析响应失败:', e);
              this.$message.error('响应格式错误');
            }
          } else {
            this.$message.error(`请求失败: ${xhr.statusText}`);
          }
        };
        
        xhr.onerror = () => {
          this.$message.error('网络请求失败');
        };
        
        xhr.send(JSON.stringify({ id: row.id }));
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    } else {
      // 归还操作 (保持原来的归还逻辑)
      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://localhost:3000/api/borrow/return');
      xhr.setRequestHeader('Content-Type', 'application/json');
      
      xhr.onload = () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
              this.$message.success(response.message);
              this.fetchBorrowList();
            } else {
              this.$message.error(response.message || '操作失败');
            }
          } catch (e) {
            console.error('解析响应失败:', e);
            this.$message.error('响应格式错误');
          }
        } else {
          this.$message.error(`请求失败: ${xhr.statusText}`);
        }
      };
      
      xhr.onerror = () => {
        this.$message.error('网络请求失败');
      };
      
      xhr.send(JSON.stringify({ id: row.id }));
    }
  }
  }
};
</script>
